package usermodel

import (
	"encoding/json"
	"fmt"
	"github.com/garyburd/redigo/redis"
	"github.com/lexkong/log"
	"stores"
)

func GetUser(username string) (*UserInfo, error) {
	u := &UserInfo{}
	d := stores.DB.Self.Where("name = ?", username).First(&u)
	log.Logger.Info(u.Name)
	return u, d.Error
}

func CheckUserNameExisted(userName string) bool {
	u := &UserInfo{}
	d := stores.DB.Self.Where("name = ?", userName).First(&u)
	if d.Error != nil {
		return false
	} else {
		return true
	}
}

func CheckPhoneExisted(phone string) bool {
	u := &UserInfo{}
	d := stores.DB.Self.Where("phone = ?", phone).First(&u)
	if d.Error != nil {
		return false
	} else {
		return true
	}
}

func CheckEmailExisted(email string) bool {
	u := &UserInfo{}
	d := stores.DB.Self.Where("email = ?", email).First(&u)
	if d.Error != nil {
		return false
	} else {
		return true
	}
}

func CreateUserInfo(user *UserInfo) bool {
	db := stores.DB.Self.Create(user)
	if db.Error != nil {
		return false
	} else {
		return true
	}
}

/**
将token放入redis
*/
func SetTokenToRedis(token string, user UserInfo) (string, error) {
	rc := stores.GetRedisCoon()
	userJson, err := json.Marshal(user)
	if err != nil {
		return "can't convert to json", err
	}
	_, err = rc.Do("SET", token, userJson)
	n, _ := rc.Do("EXPIRE", token, 7*24*3600)
	if n == int64(1) {
		fmt.Println("success")
	}
	if err != nil {
		return "can't set token redis", err
	}
	defer rc.Close()
	return "set token redis success", err
}

/**
根据token名查找redis
*/
func GetTokenFromRedis(token string) (string, error) {
	rc := stores.GetRedisCoon()
	auth, err := redis.String(rc.Do("GET", token))
	if err != nil {
		return "", err
	}
	defer rc.Close()
	return auth, err
}

/**

 */
func SetRgSmsToRds(phoneNmber string, sms CheckSendSmsRespose) (string, error) {
	rc := stores.GetRedisCoon()
	smsCode, err := json.Marshal(sms)
	if err != nil {
		return "can't convert to json", err
	}
	_, err = rc.Do("SET", phoneNmber, smsCode)
	if err != nil {
		return "can't set smsCode redis", err
	}
	defer rc.Close()
	return "set smsCode redis success", err
}

func GetRgSmsFromRds(phoneNumber string) (response *CheckSendSmsRespose, err error) {
	rc := stores.GetRedisCoon()
	res, err := redis.String(rc.Do("GET", phoneNumber))
	defer rc.Close()
	json.Unmarshal([]byte(res), &response)
	return response, err
}
func ResetPassword(id uint64, password string) bool {
	result := stores.DB.Self.Model(&UserInfo{}).Where("id=?", id).Update("password", password)
	if result.Error != nil {
		log.Logger.Info(result.Error.Error())
		return false
	} else {
		return true
	}
}

func QueryIdByPhone(phone string) *UserInfo {
	u := &UserInfo{}
	d := stores.DB.Self.Where("phone = ?", phone).First(&u)
	if d.Error != nil {
		return nil
	} else {
		return u
	}
}
